#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/10/20 20:00
# @Author  : astock
# @File    : aa.py.py
# @Software: PyCharm
import copy
import os

import pandas as pd

from models.stock_model import StockNumber, DayInfo, SHDayInfo
from mylib import download_all
from send_email import send_email_html_acc
from update_sh import get_bkd_today


def get_all_stock(names):
    res = dict()
    df = pd.read_csv('all.csv')
    count = 0
    trate_date = None
    for row in df.index:
        sn = StockNumber(df.loc[row])
        if sn.name not in names:
            continue
        download_all.get_all_stock([sn.ts_code])
        count += 1
        trate_date, v = cal_down_time_and_value(sn)
        res[(sn.name, sn.ts_code)] = v
        sort_res = sorted(res.items(), key=lambda x: (x[1][0], x[1][1]), reverse=False)
    return sn, trate_date, sort_res


def get_sh():
    """
    获取上涨涨跌幅
    """
    df_sh = pd.read_csv('shanghai_index.csv')
    down_time = 0
    maxv = 0
    minv = 0
    down_pct = 0
    today_di = None
    link_addr = f'https://xueqiu.com/S/SH000001'
    for row2 in df_sh.index:
        di = SHDayInfo(df_sh.loc[row2])
        if today_di is None:
            today_di = copy.deepcopy(di)
        if today_di.pct_chg <= 0 < di.pct_chg:
            cha = minv - maxv
            if cha:
                down_pct = f'{round(cha / maxv * 100, 2)}%'
            break
        if di.pct_chg <= 0 < today_di.pct_chg:
            cha = maxv - minv
            if cha:
                down_pct = f'{round((maxv - minv) / minv * 100, 2)}%'
            break
        if today_di.pct_chg <= 0:
            down_time -= 1
            if row2 == 0:
                maxv = di.high
                minv = di.low
            else:
                maxv = di.high if di.high > maxv else maxv
                minv = di.low if di.low < minv else minv
        else:
            down_time += 1
            if row2 == 0:
                maxv = di.high
                minv = di.low
            else:
                maxv = di.high if di.high > maxv else maxv
                minv = di.low if di.low < minv else minv
    if maxv == 0 and minv == 0:
        return down_time, down_pct, today_di.close, today_di.pct_chg, f'{maxv}-{minv}', link_addr
    return down_time, down_pct, today_di.close, today_di.pct_chg, f'{maxv}-{minv}', link_addr


def cal_down_time_and_value(sn):
    """
    计算连续下跌次数和跌幅
    :param sn:
    :return:
    """
    # 下跌/上涨次数
    down_time = 0
    maxv = 0
    minv = 0
    down_pct = 0
    trate_date = None
    today_di = None
    csv_path = f'stocks/{sn.ts_code}.csv'
    if not os.path.exists(os.path.abspath(csv_path)):
        download_all.analysis_stock(sn)
    df2 = pd.read_csv(csv_path)
    stock_number_arr = sn.ts_code.split('.')
    stock_number = f'{stock_number_arr[1]}{stock_number_arr[0]}'
    link_addr = f'https://xueqiu.com/S/{stock_number}'
    for row2 in df2.index:
        di = DayInfo(sn, df2.loc[row2])
        if trate_date is None:
            trate_date = di.trade_date
        if today_di is None:
            today_di = copy.deepcopy(di)
        if today_di.pct_chg <= 0 < di.pct_chg:
            cha = minv - maxv
            if cha:
                down_pct = round(cha / maxv * 100, 2)
            break
        if di.pct_chg <= 0 < today_di.pct_chg:
            cha = maxv - minv
            if cha:
                down_pct = round((maxv - minv) / minv * 100, 2)
            break
        if today_di.pct_chg <= 0:
            down_time -= 1
            if row2 == 0:
                maxv = di.high
                minv = di.low
            else:
                maxv = di.high if di.high > maxv else maxv
                minv = di.low if di.low < minv else minv
        else:
            down_time += 1
            if row2 == 0:
                maxv = di.high
                minv = di.low
            else:
                maxv = di.high if di.high > maxv else maxv
                minv = di.low if di.low < minv else minv
    if maxv == 0 and minv == 0:
        return trate_date, (down_time, down_pct, today_di.close, today_di.pct_chg, f'{maxv}-{minv}', link_addr)
    return trate_date, (down_time, down_pct, today_di.close, today_di.pct_chg, f'{maxv}-{minv}', link_addr)


def get_stocks(txt_path):
    with open(txt_path) as fr:
        stocks_names = [item.strip() for item in fr.readlines() if item.strip()]
        return stocks_names


def run(txt_path):
    # 持仓股定义
    stocks = get_stocks(txt_path)
    sh_info = get_sh()
    res = [(('上证指数', '000001.SH'), sh_info)]
    sn, trate_date, res2 = get_all_stock(stocks)
    for item in res2:
        res.append(item)
    send_email_html_acc.send_html(res, title=f'{trate_date}_acc_持仓股分析')


if __name__ == '__main__':
    txt_path = 'acc2.txt'
    run(txt_path)
